
// Copyright (C) 2012 Luca Piccioni
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//  
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//  
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;

using Derm.Render;
using Derm.Scene.Mesh;

namespace Derm.Xml.Collada
{
	/// <summary>
	/// Geometry describes the visual shape and appearance of an object in the scene.
	/// The geometry element categorizes the declaration of geometric information. Geometry is a 
	/// branch of mathematics that deals with the measurement, properties, and relationships of 
	/// points, lines, angles, surfaces, and solids.
	/// </summary>
	public class ColladaGeometry : ColladaXmlSerializable, IColladaInstantiable
	{
		#region Constructors

		/// <summary>
		/// Construct a ColladaGeometry.
		/// </summary>
		/// <param name="parent">
		/// The parent element containing this ColladaGeometry.
		/// </param>
		public ColladaGeometry(ColladaXmlSerializable parent) : base(parent)
		{
			
		}

		#endregion

		#region Geometry Information

		/// <summary>
		/// The id attribute is a text string containing the unique identifier of this element.
		/// This value must be unique within the instance document. Optional attribute.
		/// </summary>
		public string Id;

		/// <summary>
		/// The name attribute is the text string name of this element. Optional attribute.
		/// </summary>
		public string Name;

		/// <summary>
		/// The geometry element may contain an asset element.
		/// </summary>
		public ColladaAsset Asset;

		/// <summary>
		/// The geometry element may contain only one mesh, convex_mesh or spline.
		/// </summary>
		public ColladaMesh Mesh;

		/// <summary>
		/// The geometry element may contain only one mesh, convex_mesh or spline.
		/// </summary>
		public ColladaSpline Spline;

		/// <summary>
		/// The extra element may appear any number of times.
		/// </summary>
		public readonly List<ColladaExtra>  Extras = new List<ColladaExtra>();

		#endregion

		#region COLLADA Support

		/// <summary>
		/// Create a <see cref="Mesh"/> from this <see cref="ColladaGeometry"/>.
		/// </summary>
		internal Mesh Create(ColladaInstanceGeometry instanceGeometry)
		{
			if (instanceGeometry == null)
				throw new ArgumentNullException("instanceGeometry");

			if (Mesh != null) {
				sLog.Debug("Geometry '{0}' defined with mesh technique", Name ?? String.Empty);
				return (Mesh.Create(instanceGeometry));
			}

			throw new NotSupportedException("geometry technique not supported");
		}

		#endregion

		#region Logging

		/// <summary>
		/// Logger of this class.
		/// </summary>
		private static readonly ILogger sLog = Log.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		#endregion

		#region ColladaXmlSerializable Overrides

		/// <summary>
		/// Read the attribute of the current XML serializable.
		/// </summary>
		/// <param name="xmlReader">
		/// A <see cref="XmlReader"/> used for reading XML element attributes.
		/// </param>
		/// <remarks>
		/// <para>
		/// This method is called only in the case there are effectively attributes on XML element. Don't expect that this
		/// method will be called even when the attributes count is zero. This is very important, since the design doesn't
		/// allow object initialization using this method.
		/// </para>
		/// </remarks>
		public override void ReadAttributes(XmlReader xmlReader)
		{
			if (xmlReader == null)
				throw new ArgumentNullException("xmlReader");

			string attribute;

			if ((attribute = xmlReader[ColladaAttributeId]) != null)
				Id = attribute;
			if ((attribute = xmlReader[ColladaAttributeName]) != null)
				Name = attribute;
		}

		/// <summary>
		/// Read an element of the current XML serializable.
		/// </summary>
		/// <param name="elementName">
		/// A <see cref="System.String"/> that specify the element name.
		/// </param>
		/// <param name="xmlReader">
		/// A <see cref="XmlReader"/> used for reading child element. It is positioned at the start element.
		/// </param>
		/// <remarks>
		/// <para>
		/// This method is responsible to read the start element of the nested element.
		/// </para>
		/// <para>
		/// This method is resposible to read all children elements till the corresponding end element, without reading it. In the
		/// case this condition is not satisfied, the XML parsing will be aborted.
		/// </para>
		/// </remarks>
		public override void ReadElement(string elementName, XmlReader xmlReader)
		{
			if (elementName == null)
				throw new ArgumentNullException("elementName");
			if (xmlReader == null)
				throw new ArgumentNullException("xmlReader");

			if (elementName == ColladaElementAsset) {
				Asset = new ColladaAsset(this);
				Asset.ReadXml(xmlReader);
			} else if (elementName == ColladaElementConvexMesh) {
				XmlHelper.SkipXmlElement(xmlReader);
			} else if (elementName == ColladaElementMesh) {
				Mesh = new ColladaMesh(this);
				Mesh.ReadXml(xmlReader);
			} else if (elementName == ColladaElementSpline) {
				Spline = new ColladaSpline(this);
				Spline.ReadXml(xmlReader);
			} else if (elementName == ColladaElementExtra) {
				ColladaExtra colladaExtra = new ColladaExtra(this);
				colladaExtra.ReadXml(xmlReader);
				Extras.Add(colladaExtra);
			} else
				base.ReadElement(elementName, xmlReader);
		}

		/// <summary>
		/// Collada 'geometry' attribute name (1.4).
		/// </summary>
		private const string ColladaAttributeId = "id";

		/// <summary>
		/// Collada 'geometry' attribute name (1.4).
		/// </summary>
		private const string ColladaAttributeName = "name";

		/// <summary>
		/// Collada 'geometry' child element name (1.4).
		/// </summary>
		private const string ColladaElementAsset = "asset";

		/// <summary>
		/// Collada 'geometry' child element name (1.4).
		/// </summary>
		private const string ColladaElementConvexMesh = "convex_mesh";

		/// <summary>
		/// Collada 'geometry' child element name (1.4).
		/// </summary>
		private const string ColladaElementMesh = "mesh";

		/// <summary>
		/// Collada 'geometry' child element name (1.4).
		/// </summary>
		private const string ColladaElementSpline = "spline";

		/// <summary>
		/// Collada 'geometry' child element name (1.4).
		/// </summary>
		private const string ColladaElementExtra = "extra";

		#endregion

		#region IColladaInstantiable Implementation

		/// <summary>
		/// Instantiable identifier.
		/// </summary>
		public string InstanceId { get { return (Id); } }

		#endregion
	}

	/// <summary>
	/// The technique_common specifies the common method for accessing this source element's data.
	/// </summary>
	public class ColladaMeshCommonTechnique : ColladaXmlSerializable
	{
		#region Constructors

		/// <summary>
		/// Construct a ColladaMeshCommonTechnique.
		/// </summary>
		/// <param name="parent">
		/// The parent element containing this ColladaMeshCommonTechnique.
		/// </param>
		public ColladaMeshCommonTechnique(ColladaXmlSerializable parent) : base(parent)
		{
			
		}

		#endregion

		#region Mesh Common Technique Information

		/// <summary>
		/// The source's technique_common must have one and only one accessor.
		/// </summary>
		public ColladaAccessor Accessor;

		#endregion

		#region ColladaXmlSerializable Overrides

		/// <summary>
		/// Read an element of the current XML serializable.
		/// </summary>
		/// <param name="elementName">
		/// A <see cref="System.String"/> that specify the element name.
		/// </param>
		/// <param name="xmlReader">
		/// A <see cref="XmlReader"/> used for reading child element. It is positioned at the start element.
		/// </param>
		/// <remarks>
		/// <para>
		/// This method is responsible to read the start element of the nested element.
		/// </para>
		/// <para>
		/// This method is resposible to read all children elements till the corresponding end element, without reading it. In the
		/// case this condition is not satisfied, the XML parsing will be aborted.
		/// </para>
		/// </remarks>
		public override void ReadElement(string elementName, XmlReader xmlReader)
		{
			if (elementName == null)
				throw new ArgumentNullException("elementName");
			if (xmlReader == null)
				throw new ArgumentNullException("xmlReader");

			if (elementName == ColladaElementAccessor) {
				Accessor = new ColladaAccessor(this);
				Accessor.ReadXml(xmlReader);
			} else
				base.ReadElement(elementName, xmlReader);
		}

		/// <summary>
		/// Collada 'technique_common' child element name (1.4).
		/// </summary>
		private const string ColladaElementAccessor = "accessor";

		#endregion
	}

	/// <summary>
	/// The mesh element contains vertex and primitive information sufficient to describe basic geometric meshes.
	/// </summary>
	public class ColladaMesh : ColladaXmlSerializable
	{
		#region Constructors

		/// <summary>
		/// Construct a ColladaMesh.
		/// </summary>
		/// <param name="parent">
		/// The parent element containing this ColladaMesh.
		/// </param>
		public ColladaMesh(ColladaXmlSerializable parent) : base(parent)
		{
			
		}

		#endregion

		#region Mesh Information

		/// <summary>
		/// The mesh element must contain one or more source elements.
		/// </summary>
		public readonly List<ColladaSource> Sources = new List<ColladaSource>();

		/// <summary>
		/// The mesh element must contain one vertices element.
		/// </summary>
		public ColladaVertices Vertices;

		/// <summary>
		/// Set of collation elements.
		/// </summary>
		public readonly List<ColladaCollation> Collations = new List<ColladaCollation>();

		/// <summary>
		/// The extra element may appear any number of times.
		/// </summary>
		public readonly List<ColladaExtra> Extras = new List<ColladaExtra>();

		#endregion

		#region COLLADA Support

		/// <summary>
		/// Create a <see cref="Mesh"/> corresponding to ths <see cref="ColladaMesh"/>.
		/// </summary>
		internal Mesh Create(ColladaInstanceGeometry instanceGeometry)
		{
			if (instanceGeometry == null)
				throw new ArgumentNullException("instanceGeometry");

			Mesh mesh = new Mesh();
			Dictionary<string, ArrayBufferObject> meshBuffers = new Dictionary<string, ArrayBufferObject>();

			

			// Collect all mesh sources
			foreach (ColladaSource colladaSource in Sources) {
				if (colladaSource.CommonTechnique != null) {
					sLog.Debug("Loading mesh source buffer '{0}'", colladaSource.Id);

					ColladaAccessor sourceAccessor = colladaSource.CommonTechnique.Accessor;
					ArrayBufferObject sourceBuffer = sourceAccessor.GetAccessorArray();

					meshBuffers[colladaSource.Id] = sourceBuffer;
				}
			}

			// Include vertices semantic
			if (Vertices != null) {
				foreach (ColladaInputLocal input in Vertices.Inputs) {
					meshBuffers[Vertices.Id] = meshBuffers[GetFragmentName(input.Source)];
					sLog.Debug("Loading mesh source buffer (aliased) '{0}' pointing to '{1}'", Vertices.Id, input.Source);
				}
			}

			// Construct mesh vertex arrays
			if (Collations.Count > 0) {
				foreach (ColladaCollation colladaCollation in Collations) {
					ColladaCollationContext collationContext = new ColladaCollationContext();

					collationContext.InstanceGeometry = instanceGeometry;
					collationContext.ArrayBuffers = meshBuffers;

					sLog.Debug("Defining mesh with collation '{0}'", colladaCollation.Name);
					mesh.VertexArrays.AddVertexArray(colladaCollation.GetArrayObject(collationContext));
				}
			} else {
				throw new NotSupportedException("no collations");
			}

			return (mesh);
		}

		#endregion

		#region Logging

		/// <summary>
		/// Logger of this class.
		/// </summary>
		private static readonly ILogger sLog = Log.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		#endregion

		#region ColladaXmlSerializable Overrides

		/// <summary>
		/// Read an element of the current XML serializable.
		/// </summary>
		/// <param name="elementName">
		/// A <see cref="System.String"/> that specify the element name.
		/// </param>
		/// <param name="xmlReader">
		/// A <see cref="XmlReader"/> used for reading child element. It is positioned at the start element.
		/// </param>
		/// <remarks>
		/// <para>
		/// This method is responsible to read the start element of the nested element.
		/// </para>
		/// <para>
		/// This method is resposible to read all children elements till the corresponding end element, without reading it. In the
		/// case this condition is not satisfied, the XML parsing will be aborted.
		/// </para>
		/// </remarks>
		public override void ReadElement(string elementName, XmlReader xmlReader)
		{
			if (elementName == null)
				throw new ArgumentNullException("elementName");
			if (xmlReader == null)
				throw new ArgumentNullException("xmlReader");

			if (elementName == ColladaElementSources) {
				ColladaSource colladaSource = new ColladaSource(this);
				colladaSource.ReadXml(xmlReader);
				Sources.Add(colladaSource);
			} else if (elementName == ColladaElementVertices) {
				Vertices = new ColladaVertices(this);
				Vertices.ReadXml(xmlReader);
			} else if (elementName == ColladaElementLines) {
				ColladaCollation colladaCollation = new ColladaLines(this);
				colladaCollation.ReadXml(xmlReader);
				Collations.Add(colladaCollation);
			} else if (elementName == ColladaElementLinesStrips) {
				ColladaCollation colladaCollation = new ColladaLineStrips(this);
				colladaCollation.ReadXml(xmlReader);
				Collations.Add(colladaCollation);
			} else if (elementName == ColladaElementPolygons) {
				ColladaCollation colladaCollation = new ColladaPolygons(this);
				colladaCollation.ReadXml(xmlReader);
				Collations.Add(colladaCollation);
			} else if (elementName == ColladaElementPolyList) {
				ColladaCollation colladaCollation = new ColladaPolygonList(this);
				colladaCollation.ReadXml(xmlReader);
				Collations.Add(colladaCollation);
			} else if (elementName == ColladaElementTriangles) {
				ColladaCollation colladaCollation = new ColladaTriangles(this);
				colladaCollation.ReadXml(xmlReader);
				Collations.Add(colladaCollation);
			} else if (elementName == ColladaElementTriFans) {
				ColladaCollation colladaCollation = new ColladaTrangleFans(this);
				colladaCollation.ReadXml(xmlReader);
				Collations.Add(colladaCollation);
			} else if (elementName == ColladaElementTriStrips) {
				ColladaCollation colladaCollation = new ColladaTriangleStrips(this);
				colladaCollation.ReadXml(xmlReader);
				Collations.Add(colladaCollation);
			} else if (elementName == ColladaElementExtra) {
				ColladaExtra colladaExtra = new ColladaExtra(this);
				colladaExtra.ReadXml(xmlReader);
				Extras.Add(colladaExtra);
			} else
				base.ReadElement(elementName, xmlReader);
		}

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementSources = "source";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementVertices = "vertices";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementLines = "linestrips";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementLinesStrips = "linestrips";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementPolygons = "polygons";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementPolyList = "polylist";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementTriangles = "triangles";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementTriFans = "trifans";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementTriStrips = "tristrips";

		/// <summary>
		/// Collada 'mesh' child element name (1.4).
		/// </summary>
		private const string ColladaElementExtra = "extra";

		#endregion
	}

	/// <summary>
	/// The spline element contains control vertex information sufficient to describe basic splines.
	/// </summary>
	public class ColladaSpline : ColladaXmlSerializable
	{
		#region Constructors

		/// <summary>
		/// Construct a ColladaSpline.
		/// </summary>
		/// <param name="parent">
		/// The parent element containing this ColladaSpline.
		/// </param>
		public ColladaSpline(ColladaXmlSerializable parent) : base(parent)
		{
			
		}

		#endregion

		#region Spline Information

		#endregion
	}
}
